package com.ys.dubbo.provider.config;


import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

@Configuration
public class DubboProtocol {

    @Bean
    public RegistryConfig registry(@Value("${dubbo.registry.address}") String addr, @Value("${dubbo.zk.timeout}") Integer timeout) {
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress(addr);
        registryConfig.setTimeout(timeout);

        return registryConfig;
    }


    @Bean
    public MetadataReportConfig metadataReportConfig(@Value("${dubbo.registry.address}") String addr) {

        MetadataReportConfig metadataReportConfig = new MetadataReportConfig();
        metadataReportConfig.setAddress(addr);
        return metadataReportConfig;
    }

    @Bean
    public ConfigCenterConfig configCenterConfig(@Value("${dubbo.registry.address}") String addr) {

        ConfigCenterConfig configCenterConfig = new ConfigCenterConfig();
        configCenterConfig.setAddress(addr);
        return configCenterConfig;
    }

    @Bean
    public ApplicationConfig application(@Value("${dubbo.application.name}") String appName, @Value("${dubbo.application.owner}") String appOwner) {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName(appName);
        applicationConfig.setOwner(appOwner);
        return applicationConfig;
    }

    @Bean
    public MonitorConfig monitorConfig(@Value("${dubbo.monitor.protocol}") String protocol) {
        MonitorConfig mc = new MonitorConfig();
        mc.setProtocol(protocol);
        return mc;
    }

    @Bean
    @ConditionalOnProperty("dubbo.protocol.port")//生效条件dubbo.port有值
    public ProtocolConfig protocol(@Value("${dubbo.protocol.name:dubbo}") String name, @Value("${dubbo.protocol.port}") Integer port) {
        Assert.notNull(port, "dubbo.protocol.port  cannot be null");

        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setName(name);
        protocolConfig.setPort(port);
        return protocolConfig;
    }


}
